package com.tyk.bookstore.back.system.valid.validator;

import com.tyk.bookstore.back.system.valid.annotation.AvatarValid;
import com.tyk.bookstore.back.system.valid.constant.UserValidConstant;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class AvatarValidConstraintValidator implements ConstraintValidator<AvatarValid, MultipartFile> {

	@Override
	public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
		if (value == null) {
			return true;
		}

		return value.getSize() <= UserValidConstant.AVATAR_MAX_SIZE
				&& UserValidConstant.AVATAR_FILE_TYPE.equals(value.getContentType()) && equalsWidthAndHeight(value);
	}

	private static boolean equalsWidthAndHeight(MultipartFile img) {
		try {
			BufferedImage image = ImageIO.read(img.getInputStream());
			return image.getWidth() == UserValidConstant.AVATAR_WIDTH
					&& image.getHeight() == UserValidConstant.AVATAR_HEIGHT;
		}
		catch (IOException e) {
			throw new RuntimeException("读取图片时发生错误", e);
		}
	}

}
